package com.yang.crawler.html.parser;


import com.yang.crawler.html.dto.HtmlBlockDTO;
import com.yang.crawler.html.enums.HtmlTagEnum;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

public class HtmlBlockParser {
    public static List<HtmlBlockDTO> parseHtml(String htmlContent) {
        List<HtmlBlockDTO> htmlBlockDTOList = new ArrayList<>();
        try {
            Document document = Jsoup.parse(htmlContent);
            Elements elements = document.getAllElements();
            for (org.jsoup.nodes.Element element : elements) {
                String tagName = element.tagName();
                if (tagName == null || !HtmlTagEnum.containsTag(tagName)) {
                    continue;
                }
                String textContent = element.text();
                if ("img".equals(tagName)) {
                    textContent = element.attr("src");
                }
                HtmlTagEnum htmlTag = HtmlTagEnum.getHtmlTag(tagName);
                htmlBlockDTOList.add(new HtmlBlockDTO(htmlTag, textContent));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return htmlBlockDTOList;
    }
}

